// pages/user/favorite.js
const api = require('../../utils/api');
const utils = require('../../utils/index');

Page({
  data: {
    isLoggedIn: false,
    favoriteStores: [],
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 10,
    total: 0
  },

  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '收藏门店',
    });
    
    // 检查登录状态
    this.checkLoginStatus();
  },
  // 下拉刷新
  onPullDownRefresh: function() {
    // 重置分页数据
    this.setData({
      page: 1,
      hasMore: true,
      favoriteStores: []
    });

    // 重新加载数据
    this.loadFavoriteStores();
  },

  // 检查登录状态
  checkLoginStatus: function() {
    const token = wx.getStorageSync('token');
    if (token) {
      this.setData({ isLoggedIn: true });
      // 加载收藏门店列表
      this.loadFavoriteStores();
    } else {
      this.setData({ isLoggedIn: false });
    }
  },

  // 加载收藏门店列表
  loadFavoriteStores: function () {
    if (this.data.loading || !this.data.hasMore) {
      return;
    }
    this.setData({ loading: true });
    api.user.getFavoriteList({
      page: this.data.page,
      page_size: this.data.pageSize
    }).then(res => {
      if (res.success) {
        const newStores = res.data.list || [];
        const formattedStores = newStores.map(store => {
          // 格式化收藏时间
          const favoriteTime = store.favorite_at ? utils.formatTimestampWithTime(store.favorite_at) : '-';
          
          return {
            ...store,
            favoriteTime: favoriteTime
          };
        });
        
        // 更新数据
        const currentStores = this.data.favoriteStores || [];
        this.setData({
          favoriteStores: [...currentStores, ...formattedStores],
          page: this.data.page + 1,
          hasMore: formattedStores.length >= this.data.pageSize,
          total: res.data.total || 0
        });
      } else {
        wx.showToast({
          title: res.message || '获取收藏门店失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('获取收藏门店失败', err);
      wx.showToast({
        title: '网络错误，请稍后再试',
        icon: 'none'
      });
    }).finally(() => {
      this.setData({ loading: false });
      wx.stopPullDownRefresh();
    });
  },

  // 取消收藏
  onTapCancelFavorite: function (e) {
    const storeId = e.currentTarget.dataset.id;
    
    wx.showModal({
      title: '提示',
      content: '确定取消收藏该门店吗？',
      success: (res) => {
        if (res.confirm) {
          api.user.cancelFavorite(storeId).then(res => {
            if (res.success) {
              wx.showToast({
                title: '取消收藏成功',
                icon: 'success'
              });
              
              // 从列表中移除该门店
              const updatedStores = this.data.favoriteStores.filter(store => store.id !== storeId);
              this.setData({
                favoriteStores: updatedStores,
                total: this.data.total - 1
              });
            } else {
              wx.showToast({
                title: res.message || '取消收藏失败',
                icon: 'none'
              });
            }
          }).catch(err => {
            console.error('取消收藏失败', err);
            wx.showToast({
              title: '网络错误，请稍后再试',
              icon: 'none'
            });
          });
        }
      }
    });
  },

  onTapBack: function () {
    // 返回上一页
    wx.navigateBack({
      delta: 1,
      fail: function (res) {
        console.log('返回失败', res);
        wx.reLaunch({
          url: '/pages/user/index'
        });
      }
    });
  },

  onTapStore: function (e) {
    // 获取门店ID
    const storeId = e.currentTarget.dataset.id;
    
    // 跳转到门店详情页面
    wx.reLaunch({
      url: `/pages/venue/room?id=${storeId}`,
      fail: function (res) {
        console.log('跳转失败', res);
        wx.showToast({
          title: '跳转失败',
          icon: 'none'
        });
      }
    });
  },
  
  // 前往登录
  onTapLogin: function() {
    wx.navigateTo({
      url: '/pages/user/login',
      success: () => {
        console.log('跳转到登录页面成功');
      },
      fail: (err) => {
        console.error('跳转到登录页面失败', err);
      }
    });
  },
  
  // 下拉刷新
  onPullDownRefresh: function() {
    // 重置分页数据
    this.setData({
      page: 1,
      hasMore: true,
      favoriteStores: []
    });
    
    // 重新加载数据
    this.loadFavoriteStores();
  },
  
  // 上拉加载更多
  onReachBottom: function() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadFavoriteStores();
    }
  }
});